#include "db.h"
#include "global.h"
#include "user.h"
#include <QList>
#include <QQmlEngine>
#include <QVariantMap>
#include <QDateTime>
#include <QJsonObject>

User::User(QObject *parent)
    : QAbstractListModel(parent)
{
    qDebug() << __FUNCTION__ << __LINE__;
    // 可以立即加载初始数据
    DB* db = DB::getInstance();
    m_roles = db->getTableFieldRole("user");
    loadUser("");
}

int User::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) return 0;
    return m_records.size();
}

QVariant User::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_records.size())
        return QVariant();

    //qDebug() << __FUNCTION__ << __LINE__ << "role:" << role << "-index:" << index.row();
    const QHash<QString, QVariant> has = m_records[index.row()];

    return has[m_roles[role]];
}

QHash<int, QByteArray> User::roleNames() const
{
    qDebug() << __FUNCTION__ << __LINE__ ;
    return m_roles;
}

void User::addRecord(const QString &name, const QString password, const QString &real_name, const QString &expiration, const QString &status, const QString &permission, const QString &create_by)
{
    qDebug() << __FUNCTION__ << __LINE__;

    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    DB::getInstance()->addUser(name, password, real_name, expiration, status, permission, create_by);
    QJsonObject jsonObj;
    jsonObj["name"] = name;                  // 整数
    jsonObj["password"] = password;              // 字符串
    jsonObj["real_name"] = real_name;                    // 布尔值
    jsonObj["expiration"] = expiration;                // 浮点数
    jsonObj["status"] = status;
    jsonObj["permission"] = permission;
    jsonObj["create_by"] = create_by;


    User* pUser = (User*)Global::instance().get("userInfo");
    QString loginName = pUser->currentLogin()["name"].toString();
    QString realName = pUser->currentLogin()["real_name"].toString();

    QJsonDocument jd(jsonObj);
    DB::getInstance()->addLog(loginName, realName, "添加用户", "添加成功["+name+"]", jd.toJson(QJsonDocument::Indented), loginName);
    endInsertRows();
}

void User::removeRow(int row)
{
    qDebug() << __FUNCTION__ << __LINE__;
    if (row < 0 || row >= m_records.size()) return;
    beginRemoveRows(QModelIndex(), row, row);
    m_records.removeAt(row);
    endRemoveRows();
}

void User::updateRow(int row, const QVariantMap &newData)
{
    qDebug() << __FUNCTION__ << __LINE__;
    if (row < 0 || row >= m_records.size()) return;
    // 合并新数据到内存模型
    QHash<QString, QVariant> &record = m_records[row];
    for (auto it = newData.begin(); it != newData.end(); ++it) {
        record[it.key()] = it.value();
    }
    // 持久化到数据库
    DB::getInstance()->updateUser(
        record["id"].toString(),
        record["name"].toString(),
        record["password"].toString(),
        record["real_name"].toString(),
        record["expiration"].toString(),
        record["status"].toString(),
        record["permission"].toString(),
        m_login["name"].toString()
    );

    // 同步内存模型中的修改时间，避免显示滞后一拍
    record["update_time"] = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    QJsonObject jsonObj;
    jsonObj["id"]   = record["id"].toString();
    jsonObj["name"] = record["name"].toString();                  // 整数
    jsonObj["password"] = record["password"].toString();              // 字符串
    jsonObj["real_name"] = record["real_name"].toString();                    // 布尔值
    jsonObj["expiration"] = record["expiration"].toString();                // 浮点数
    jsonObj["status"] = record["status"].toString();
    jsonObj["permission"] = record["permission"].toString();
    jsonObj["create_by"] = record["create_by"].toString();

    User* pUser = (User*)Global::instance().get("userInfo");
    QString loginName = pUser->currentLogin()["name"].toString();
    QString realName = pUser->currentLogin()["real_name"].toString();

    QJsonDocument jd(jsonObj);
    //DB::getInstance()->addLog("modifyUser", record["name"].toString(), record["password"].toString(), jd.toJson(QJsonDocument::Indented) , m_login["name"].toString());
    DB::getInstance()->addLog(loginName, realName, "修改用户", "修改成功["+record["name"].toString()+"]" , jd.toJson(QJsonDocument::Indented), loginName);

    QModelIndex idx = this->index(row, 0);
    emit dataChanged(idx, idx, roleNames().keys());
}

int User::count() const
{
    qDebug() << __FUNCTION__ << __LINE__;
    return m_records.size();
}

QVariantMap User::get(int row) const
{
    qDebug() << __FUNCTION__ << __LINE__;
    QVariantMap result;
    if (row < 0 || row >= m_records.size())
        return result;
    const QHash<QString,QVariant> &record = m_records[row];
    for (auto it = record.begin(); it != record.end(); ++it) {
        result[it.key()] = it.value();
    }
    return result;
}

void User::setProperty(int row, const QString &role, const QVariant &value)
{
    qDebug() << __FUNCTION__ << __LINE__;
    if (row < 0 || row >= m_records.size())
        return;
    // 更新内存模型的指定字段
    m_records[row][role] = value;
    // 通知视图数据已更改
    QModelIndex idx = this->index(row, 0);
    emit dataChanged(idx, idx, {});
}

void User::loadUser(const QString& filter)
{
    qDebug() << __FUNCTION__ << __LINE__;
    DB* db = DB::getInstance();
    beginResetModel();
    m_records = db->queryUsers(filter);
    endResetModel();
}

QHash<QString,QVariant> User::login(const QString &name, const QString &password)
{
    m_login.clear();
    foreach (const auto& hs, m_records) {
        if (hs["name"].toString().compare(name) == 0 && hs["password"].toString().compare(password) == 0) {
            m_login = hs;

//            DB::getInstance()->addLog("loginSystem", m_login["name"].toString(), "success", "login success" , m_login["name"].toString());
            DB::getInstance()->addLog(hs["name"].toString(), hs["real_name"].toString(), "用户登录", "登录成功" , "", hs["name"].toString());
            qDebug() << __FUNCTION__ << __LINE__ << hs["name"] << ":" << hs["password"] << "登录成功状态:"<< hs["status"];
            emit currentLoginChanged();
            return m_login;
        }
    }
    qDebug() << __FUNCTION__ << __LINE__ << "登录失败：" << name;
    return m_login;
}

bool User::modifyPassword(const QString &password)
{
    DB* db = DB::getInstance();
    qDebug() << "modifyPassword>>>>>>";
    if(db->modifyPassword(m_login["id"].toString(), password)){
        m_login["password"] = password;
        //DB::getInstance()->addLog("modifyPassword", m_login["name"].toString(), "success", password , m_login["name"].toString());
        DB::getInstance()->addLog(m_login["name"].toString(), m_login["real_name"].toString(), "修改密码", "修改成功" , password, m_login["name"].toString());
    }
    for (QHash<QString,QVariant>& hs: m_records) {
        if (hs["id"].toString().compare(m_login["id"].toString()) == 0) {
            hs["password"] = password;
            break;
        }
    }

    return true;
}

bool User::isFirstLogin()
{
    qDebug() << "modifyPassword>>>>>>";
    return !(DB::getInstance()->isExist(m_login["name"].toString(), "修改密码", "修改成功")>0);
}

bool User::hasBeenUsed(int count, const QString &password)
{
    return DB::getInstance()->hasBeenUsed(count, password, "modifyPassword", m_login["name"].toString(), "success");
}

void User::clear()
{
    if (m_records.isEmpty()) return;
    beginResetModel();
    m_records.clear();
    endResetModel();
}
